﻿#include "guild_building_logic.h"

#include "GuildBuilding_struct.h"
#include "GuildModuleBuilding_struct.h"

#include "error/make_error_code.h"
#include "guild/module/guild_module.h"
#include "guild/module/guild_module_loader.hpp"
#include "guild/guild_loader.hpp"

#include "GuildBuildingUpgradeArg_struct.h"
#include "GuildBuildingUpgradeRes_struct.h"

#include "guildservicetimer.service.GuildServiceTimer.proxy.h"

namespace guild_service {
bool GuildModuleBuildingLogic::BuildingUpgrade(const role_uuid_type role_uuid,
                                               uint32_t building_id,
                                               error_code &ec) {
  if (role_uuid == kInvalidRoleUuid) {
    ec = ErrorCode::ERR_INVALID_ROLE_UUID;
    return false;
  }

  guild_id_type guild_id = kInvalidGuildId;
  if (!detail::LoadGuildIdByRole(kGuildServiceBuildingName, role_uuid,
                                 guild_id)) {
    ec = ErrorCode::ERR_GUILD_NOT_EXIST;
    return false;
  }

  {
    GuildModuleBuilding module_building;
    if (!detail::GetGuildModule<GuildModuleBuilding>(
            kGuildServiceBuildingName, guild_id, kGuildModuleBuildingName,
            module_building)) {
      ec = ErrorCode::ERR_GUILD_MOD_BUILDING_LOAD_FAILED;
      return false;
    }

    const auto &building_dic = module_building.building_dic;
    const auto it = building_dic.find(building_id);
    if (it == building_dic.end()) {
      ec = ErrorCode::ERR_GUILD_MOD_BUILDING_BUILDING_NOT_EXIST;
      return false;
    }

    if (it->second.is_upgrading) {
      ec = ErrorCode::ERR_GUILD_MOD_BUILDING_UPGRADING;
      return false;
    }

    constexpr uint32_t building_max_level = 10;
    if (it->second.level >= building_max_level) {
      ec = ErrorCode::ERR_GUILD_MOD_BUILDING_TOP_LEVEL_LIMITED;
      return false;
    }
  }

  auto prx_timer_ptr = ServiceContextSingleton()->get_proxy_co<GuildServiceTimerProxy>(2000);
#ifdef DEBUG
  assert(prx_timer_ptr);
#endif // DEBUG
  if (!prx_timer_ptr) {
    ec = ErrorCode::ERR_GUILD_MOD_BUILDING_UPGRADE_FAILED;
    return false;
  }

  GuildBuildingUpgradeArg arg;
  arg.building_id = building_id;
  arg.guild_id = guild_id;
  arg.level = 1;
  auto res = prx_timer_ptr->GuildBuildingUpgrade(arg);

  ec = static_cast<ErrorCode>(res->result);


  return true;
}
}  // guild_service